# 导入序列比对库
import difflib
# 从 pygments 库导入语法高亮相关模块
from pygments import highlight
from pygments.formatters import HtmlFormatter
from pygments.lexers import get_lexer_by_name

# 创建 HTML 格式化器实例
formatter = HtmlFormatter(cssclass='highlight', nowrap=True)

from difflib import ndiff


def generate_diff_output(old, new, diff_only, lang):
    l, r = [], []
    old_lines = old
    new_lines = new
    diff = ndiff(old_lines, new_lines)
    left_line_num = 1
    right_line_num = 1
    
    for line in diff:
        if line.startswith('- '):
            content = line[2:]
            num = f"<span class='line-number'>{left_line_num}</span>"
            sym = f"<span class='line-symbol'>-</span>"
            l.append(f"<div class='diff-removed'>{num}{sym}{content}</div>")
            r.append(f"<div class='empty-line'></div>")
            left_line_num += 1
        elif line.startswith('+ '):
            content = line[2:]
            num = f"<span class='line-number'>{right_line_num}</span>"
            sym = f"<span class='line-symbol'>+</span>"
            l.append(f"<div class='empty-line'></div>")
            r.append(f"<div class='diff-added'>{num}{sym}{content}</div>")
            right_line_num += 1
        elif line.startswith('? '):
            continue
        else:
            if not diff_only:
                content = line[2:]
                num = f"<span class='line-number'>{left_line_num}</span>"
                sym = f"<span class='line-symbol'> </span>"
                l.append(f"<div class='diff-unchanged'>{num}{sym}{content}</div>")
                r.append(f"<div class='diff-unchanged'>{num}{sym}{content}</div>")
            left_line_num += 1
            right_line_num += 1
    
    return ''.join(l), ''.join(r)
